<?php

namespace app\admin\controller;

use app\admin\model\OrderGoods;
use app\admin\model\SystemAdmin;
use app\admin\service\ArrayService;
use app\admin\service\DictService;
use app\admin\service\ExcelService;
use app\common\controller\AdminController;
use app\common\service\HttpService;
use app\common\service\WdtService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;

use think\App;
use think\facade\Db;
use think\Request;
use function Qcloud\Cos\startWith;

/**
 * @ControllerAnnotation(title="订单管理")
 */
class Order extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Order();

        $this->assign('getMerchantStatusList', $this->model->getMerchantStatusList());

    }


    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            OrderGoods::whereIn('order_id', $id)->delete();
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data_list = DictService::getAll();
            foreach ($list as $key => $item) {
                $list[$key]['platform_id'] = ArrayService::getValue(ArrayService::getValue($data_list, 'platform_id'), $item['platform_id']);
                $list[$key]['payment_method'] = ArrayService::getValue(ArrayService::getValue($data_list, 'payment_method'), $item['payment_method']);
                $list[$key]['quality_problem'] = ArrayService::getValue(ArrayService::getValue($data_list, 'quality_problem'), $item['quality_problem']);
                $list[$key]['supplier_name'] = ArrayService::getValue(ArrayService::getValue($data_list, 'supplier_name'), $item['supplier_name']);

            }
            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            // die(var_dump($post['goods']));
            $rule = [
                'goods|商品信息'      => 'require',
            ];

            $this->validate($post, $rule);
            try {
                $post['registrant'] = session('admin.nickname');
                $post['handler'] = $this->getAdminName($post['admin_id']);
                $save = $this->model->save($post);
                $goods_model = new OrderGoods();
                $list = [];
                foreach ($post['goods'] as $good) {
                    $good['order_id'] = $this->model->id;
                    $list[] = $good;
                }
                $goods_model->saveAll($list);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function addOld()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            // die(var_dump($post['goods']));
            $rule = [
                'goods|商品信息'      => 'require',
            ];

            $this->validate($post, $rule);
            try {
                $post['registrant'] = session('admin.nickname');
                $post['handler'] = $this->getAdminName($post['admin_id']);
                $save = $this->model->save($post);
                $goods_model = new OrderGoods();
                $list = [];
                foreach ($post['goods'] as $good) {
                    $good['order_id'] = $this->model->id;
                    $list[] = $good;
                }
                $goods_model->saveAll($list);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {

        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            // die(var_dump($post));

            $rule = [
                'goods|商品信息'      => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $goods = $post['goods'];
                unset($post['goods']);
                OrderGoods::where('order_id', '=', $id)->delete();
                $goods_model = new OrderGoods();
                $goods_model->saveAll($goods);
                $post['handler'] = $this->getAdminName($post['admin_id']);
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row['platform_id'] = DictService::getData('platform_id', $row['platform_id']);
        $this->assign('row', $row);
        return $this->fetch();
    }

    private function getAdminName($id)
    {
        $handler = '';
        if ($id) {
            $admin = SystemAdmin::find($id);
            if ($admin) {
                $handler = $admin['nickname'];
            }
        }
        return $handler;
    }

    /**
     * @NodeAnotation(title="查询订单号")
     */
    public function query($trade_no = '',$logistics_no='')
    {
        if (empty($trade_no)&&empty($logistics_no)) {
            return json(HttpService::getError('参数不能为空'));
        }

if($trade_no)
        $result = WdtService::queryOrderRes($trade_no);
else
    $result = WdtService::queryOrderRes($logistics_no,2);
        if ($result['total_count'] == 0) {
            return json(HttpService::getError('未找到订单'));
        }
        $order = $result['trades'][0];
        $order['platform_name'] = DictService::getData('platform_id', $order['platform_id']);
        return json(HttpService::getSuccess($order));
    }
    /**
     * @NodeAnotation(title="查询旧账号订单")
     */
    public function queryOld($trade_no = '',$logistics_no='')
    {
        if (empty($trade_no)&&empty($logistics_no)) {
            return json(HttpService::getError('参数不能为空'));
        }

        if($trade_no)
            $result = WdtService::queryOldOrderRes($trade_no);
        else
            $result = WdtService::queryOldOrderRes($logistics_no,2);
        if ($result['total_count'] == 0) {
            return json(HttpService::getError('未找到订单'));
        }
        $order = $result['trades'][0];
        $order['platform_name'] = DictService::getData('platform_id', $order['platform_id']);
        return json(HttpService::getSuccess($order));
    }

    /**
     * @NodeAnotation(title="查询订单商品")
     */
    public function goods($order_id)
    {
        $list = OrderGoods::where('order_id', $order_id)->select();
        return json(HttpService::getSuccess($list));
    }

    /**
     * @NodeAnotation(title="查询所有字典")
     */
    public function dict()
    {
        $list=DictService::getAll();
        $list['admin_id']=   SystemAdmin::


            where('auth_ids',7)

            ->column('id,nickname','id');
        $admins=[];
        foreach ($list['admin_id'] as $item) {
            $admins[$item['id']]=$item['nickname'];
        }
        $list['admin_id']=$admins;
        return json(HttpService::getSuccess($list));
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export($is_img = 0)
    {
        list($page, $limit, $where) = $this->buildTableParames();

        $header = [

            ["处理状态", "merchant_status"],
            ["问题类型", "quality_problem"],
            ["处理人", "handler"],
            ["店铺名称", "shop_name"],
            ["订单编号", "trade_no"],

            ["支付时间", "pay_time"],
            ["物流单号", "logistics_no"],
            ["商品名称", "goods_name"],
            ["订单总价", "receivable"],
            ["打款方式", "payment_method"],

            ["商家赔付", "store_indemnity"],
            ["客服备注", "cs_remark"],
            ["规格编码", "spec_no"],
            ["反馈产品数量", "feedback_num"],
            ["商品总价", "total_price"],

            ["登记人", "registrant"],
            ["登记日期", "create_time"],
            ["平台名称", "platform_id"],

            // ["条形码", "barcode"],
            // ["商品单价", "price"],
            // ["反馈产品数量", "feedback_num"],
            // ["数量", "num"],
            // ["供应商名称", "supplier_name"],
            // ["供应商价格", "supplier_price"],


        ];

        if ($is_img) {
            $header = array_merge($header,
                [["图片凭证1", "images1"],
                    ["图片凭证2", "images2"],
                    ["图片凭证3", "images3"],
                    ["图片凭证4", "images4"],
                    ["图片凭证5", "images5"],
                    ["图片凭证6", "images6"]
                ]
            );
        }
// die(var_dump($header));
        $list = $this->model
            ->where($where)
            ->with('goodsList')
            ->limit(100000)
            ->order('id', 'desc')
            ->select()
            ->toArray();
// die(var_dump($list));
        // die(var_dump(root_path('public').'upload\20231026\08263c586860687faf4289e4a80cf66f.png'));
        $data_list = DictService::getAll();
        $result_list = [];
        foreach ($list as $key => $item) {

            $item['platform_id'] = ArrayService::getValue(ArrayService::getValue($data_list, 'platform_id'), $item['platform_id']);
            $item['payment_method'] = ArrayService::getValue(ArrayService::getValue($data_list, 'payment_method'), $item['payment_method']);

            $item['merchant_status'] = $this->getMerchantStatus($item['merchant_status']);
            if ($is_img) {
$image_list=[];
                if ($item['images']) {
                    $imgs = explode('|', $item['images']);
                    $index = 1;
                    foreach ($imgs as $image) {
                        $image_list['images' . $index] = $this->getPath($image);
                        // $header[]= ["其他凭证".$index, "images".$index];
                        $index++;
                    }
                }
                // if($item['pay_images']){
                //     $imgs=explode('|',$item['pay_images']);
                //     $pindex=1;
                //     foreach ($imgs as $image) {
                //         $list[$key]['pay_images'.$pindex]=  $this->getPath($image);
                //         // $header[]= ["赔付凭证".$pindex, "pay_images".$pindex];
                //         $pindex++;
                //     }
                // }
            }

            if ($item['goodsList']) {
                $goods_index = 0;
                foreach ($item['goodsList'] as $good) {
                    $new_item=$item;
                    if($is_img&&count($image_list)>0){
                    if ($goods_index == 0) {
                        $new_item=array_merge($item,$image_list);
                    } else {

                    }

                    }
                    $result_list[] = array_merge($new_item, [
                        'goods_name' => $good['goods_name'],
                        'feedback_num' => $good['feedback_num'],
                        'spec_no' => $good['spec_no'],
                        'quality_problem' => ArrayService::getValue(ArrayService::getValue($data_list, 'quality_problem'), $good['quality_problem']),
                        'total_price' => $good['total_price'],
                    ]);
                    $goods_index++;
                }
            } else {
                $result_list[] = $item;
            }
            // $list[$key]['supplier_name']= ArrayService::getValue(ArrayService::getValue($data_list,'supplier_name'),$item['supplier_name']);

        }
        // die(var_dump($result_list[0]));
        $fileName = "订单" . date("YmdHis");
        return ExcelService::exportData($result_list, $header, $fileName, 'xlsx', '',
            [19,20,21, 22, 23, 24]
        );
    }

    private function getPath($p)
    {
        $pattern = '/^https?:\/\/[^\/]+/i';
        $replacement = '';

        $p = preg_replace($pattern, $replacement, $p);

        return root_path() . 'public' . str_replace('/', DS, $p);
    }

    /**
     * @NodeAnotation(title="导入模板")
     */
    public function importTpl()
    {
        return download(root_path('public') . '订单导入模板.xlsx', '订单导入模板.xlsx');
    }

    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {
        // return json(HttpService::getSuccess());
        $data = [
            // 'upload_type' => $this->request->post('upload_type'),
            'file' => $this->request->file('file'),
        ];
        $file = $data['file'];
        if (empty($file)) {
            return json(HttpService::getError('请上传文件'));
        }
        $rule = [

            'file|文件' => "require|file|fileExt:xlsx,xls,csv",
        ];
        $this->validate($data, $rule);

        $returnData = ExcelService::importFile($file, 1, true);


        unset($returnData[0]);

        // die(var_dump($returnData));
        $data_list = DictService::getAll(true);
        $errors = [];
        $index = 2;
        $insert_phone = [];
        Db::startTrans();
        try {
            foreach ($returnData as $item) {
                if (empty($item[0])) {
                    if (empty($item[1]) && empty($item[2]) && empty($item[3]) && empty($item[4])) {
                        $index++;
                        continue;
                    }
                    $errors[] = '第' . $index . "行，" . "订单号不能为空";
                    $index++;
                    continue;
                }
                $merchant_status= $this->getMerchantStatusValue($item[0]);

                $quality_problem = ArrayService::getValue(ArrayService::getValue($data_list, 'quality_problem'), $item[1]);
                $trade_no=$item[4];

                $payment_method = ArrayService::getValue(ArrayService::getValue($data_list, 'payment_method'), $item[9]);
                $feedback_num=$item[13];
$total_price= $item[14];
                $platform_id = ArrayService::getValue(ArrayService::getValue($data_list, 'platform_id'), $item[17]);

                $images = join('|', $this->getImages($item, 18, 6));


                $insert_phone = [
                    'merchant_status' =>$merchant_status,
                    'quality_problem' => $quality_problem,

                    'handler' => $item[2],

                    'shop_name' => $item[3],
                    'trade_no' => $trade_no,
                    'pay_time' => $item[5],

                    'logistics_no' => $item[6],
                    'goods_name' => $item[7],
                    'receivable' => $item[8],
                    'payment_method' => $payment_method,

                    'store_indemnity' => $item[10],
                    'cs_remark' => $item[11],
                    'spec_no' => $item[12],
                    // 'feedback_num' => $item[13],
                    // 'total_price' => $item[14],

                    'registrant' => $item[15],
                    'create_time' => $item[16],
                    'platform_id' => $platform_id,

                    'images' => $images,

                ];

                //查询订单是否存在
               $order_row= \app\admin\model\Order::where('trade_no',$trade_no)->find();
               if($order_row){
                   $order_id=$order_row['id'];
               }else{
                   $admin=SystemAdmin::where('nickname',$insert_phone['handler'])->find();
                   if($admin){
                       $insert_phone['admin_id']=$admin['id'];
                   }
                $model = \app\admin\model\Order::create($insert_phone);
                   $order_id= $model->id;
               }

                OrderGoods::create([
                    'order_id' =>$order_id,
                    'goods_name' => $insert_phone['goods_name'],
                    'spec_no' => $insert_phone['spec_no'],
                    'quality_problem' => $insert_phone['quality_problem'],
                    'total_price' =>$total_price,
                    'feedback_num' =>$feedback_num,
                ]);
                $index++;
            }
            // $order_model=new \app\admin\model\Order();
            // $order_model->saveAll($insert_phone);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(HttpService::getError('系统错误' . $e->getMessage()));
        }
        $count = count($errors);
        if ($count > 0) {

            return json(HttpService::getError('导入失败' . $count . "条", join('<br/>', $errors)));
        }
        return json(HttpService::getSuccess());
    }

    private function getImages($item, int $start, int $len)
    {
        $images = [];
        for ($i = $start; $i < $start + $len; $i++) {
            if ($item[$i]) {
                $images[] = $item[$i];
            }
        }
        return $images;

    }

    /**
     * @NodeAnotation(title="客服列表")
     */
    public function handlers()
    {
        $list = SystemAdmin::where('auth_ids', 7)->field('id,nickname')->select();
        $this->success('', $list);
    }

    private function getMerchantStatus($merchant_status)
    {
        return ['待反馈', '已反馈'][$merchant_status];
    }

    private function getMerchantStatusValue($status)
    {
        $a=['待反馈'=>0, '已反馈'=>1];
        $v=ArrayService::getValue($a,$status);
        if(empty($v)){
            return 0;
        }
        return $v;
    }
}
